package cn.dglydrpy.study.j2ee.servlet.day06;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dglydrpy.study.j2ee.servlet.util.CookieUtils;
/*
 * 实现功能：查找当前浏览器有木有一个名字为username的cookie,如果没有就添加一个默认的用户名，有的话就把它和它的值显示在浏览器(只显示这个cookie)
 */
public class CookieServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//不使用工具类直接写
		/*
	    Cookie c = new Cookie("username", URLEncoder.encode("默认","UTF-8") );
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		
		Cookie[] cookies = request.getCookies();//查询cookie
		if(cookies==null){//可能是空值
			response.addCookie(c);
			System.out.println("cookie为空，已添加默认cookie");
			return;
		//cookie有值
		for (Cookie cookie : cookies) {//遍历对比
			if("username".equals(cookie.getName())){
				out.println("username: "+URLDecoder.decode(cookie.getValue(), "utf-8") );
				return;
				}
			}
		response.addCookie(c);
		System.out.println("cookie里没有username，已添加默认cookie");
		}*/
		
		//利用封装来重写
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String result = CookieUtils.findCookieByName("username", request);
		if (result == null) {
			CookieUtils.addCookie("username", "默认值", request.getContextPath(), -1, response);
		} else {
			out.println("username"+": "+result);
		}	
	}
}
